package com.example.ninepathdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private List<Msg> msgList = new ArrayList<>();

    private EditText inputText;

    private Button send;

    private RecyclerView msgRecylerView;

    private MsgAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initMsg();
        inputText = (EditText)findViewById(R.id.input_text);
        send = (Button)findViewById(R.id.send); // 发送按钮
        msgRecylerView = (RecyclerView)findViewById(R.id.msg_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);

        msgRecylerView.setLayoutManager(layoutManager);
        adapter = new MsgAdapter(msgList);
        msgRecylerView.setAdapter(adapter);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputText.getText().toString();
                if(!"".equals(content)){
                    Msg msg = null;
                    if(System.currentTimeMillis() % 2==0){
                        msg = new Msg(content,Msg.TYPE_SENT);
                    }else {
                        msg = new Msg(content,Msg.TYPE_RECEIVED);
                    }
                    msgList.add(msg);
                    adapter.notifyItemInserted(msgList.size() -1 );
                    msgRecylerView.scrollToPosition(msgList.size()-1);
                    inputText.setText(""); // 清空发送的信息
                }
            }
        });
    }

    private void initMsg () {
        Msg msg1 = new Msg("你好韩梅梅",Msg.TYPE_SENT);
        Msg msg2 = new Msg("你好李雷",Msg.TYPE_RECEIVED);
        Msg msg3 = new Msg("你在干嘛呢？",Msg.TYPE_SENT);
        msgList.add(msg1);
        msgList.add(msg2);
        msgList.add(msg3);
    }
}
